from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from datetime import datetime

class BlogModel(models.Model):
    class Meta:
        abstract = True
    created_at = models.DateTimeField('created at', auto_now_add = True)


class Category(BlogModel):
    name = models.CharField(max_length = 255)

    def get_absolute_url(self):
        return reverse('category_detail', kwargs = {'category_id':self.id})

    def __unicode__(self):
        return unicode(self.name)


class Post(BlogModel):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length = 255)
    content = models.TextField()
    public = models.BooleanField(default = True)

    class Meta:
        permissions = (
            ('view_private_post', 'Can see the private posts'),
        )

    @staticmethod
    def get_by_user(user):
        if user.has_perm('blog.view_private_posts'):
            posts = Post.objects.all()
        else:
            posts = Post.objects.filter(public = True)
        return posts.order_by('-created_at')


    def has_similar_comments(self, comment ,delta):
        return Comment.objects.filter(
            post            = comment.post,
            name            = comment.name,
            email           = comment.email,
            content         = comment.content,
            created_at__gte = datetime.now() - delta
        ).order_by('-created_at').count() > 0

    def get_absolute_url(self):
        return reverse('post_detail', kwargs = {'post_id':self.id})

    def is_created_recently(self):
        return self.created_at >= timezone.now() - datetime.timedelta(days = 1)

    is_created_recently.admin_order_field = 'created_at'
    is_created_recently.boolean = True
    is_created_recently.short_description = 'Created recently?'

    def __unicode__(self):
        return unicode(self.title)

class Comment(BlogModel):
    post = models.ForeignKey(Post)
    name = models.CharField(max_length=50)
    email = models.EmailField()
    content = models.TextField(max_length=1000)

    def __unicode__(self):
        return unicode(self.id)